const http = require('http');
const fs = require(`fs`);
const path = require('path');

let options = {
    hostname: 'localhost',
    port: 8080,
    path: '/',
    method: 'GET'
}

let start = 0, speed = 100000, end = start + speed;
let ws = fs.createWriteStream('./download.png');

function download() {
    options.headers = {
        Range: `bytes=${start}-${end}`
    };
    http.get(options, res => {
        let total = parseInt(res.headers['content-range'].split('/')[1]);
        // 字符
        let buffers = [];
        res.on('data', (chunk) => {
            buffers.push(chunk);
        })
        //传输完成
        res.on('end', () => {
            // 写入
            ws.write(Buffer.concat(buffers));
            // 下一个请求
            start = end + 1;
            let nextEnd = end + speed;
            end = nextEnd < total ? nextEnd : total;
            if (start < end)
                download();
        })
    })
}


download();